﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mrhd.Application;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Mrhd.Web.Core
{
    [AppStartup(10)]
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();
            // 添加JWT验证，默认所有请求均开启验证
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);

            //services.AddCorsAccessor();

            services.AddControllers()
                    .AddInjectWithUnifyResult()
                    // 使用Newtonsoft.Json
                    .AddNewtonsoftJson(option =>
                    {
                        option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
                        option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";             // 时间格式
                        //option.SerializerSettings.ContractResolver = new DefaultContractResolver();     // 原样输出属性名
                    });

            // 使用Redis作为分布式缓存
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = App.Configuration["Redis:Connection"];
                options.InstanceName = App.Configuration["Redis:Prefix"];
            });

            // 注册远程请求
            services.AddRemoteRequest();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            //app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();
            
            // 使用Furion
            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}